﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xlit.Utility;

namespace Xlit.ConsoleApp
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var url = "http://121.40.77.152:8081/api/values/post03";
            var header = new Dictionary<string, string>
                {
                    { "Content-Type", "application/json" }
                };
            var param = "{\"param01\":\"p01\", \"param02\":\"p02\"}";
            var response = await PostAsync(url, param, header);

            var responseHeaderText = "";
            foreach (var h in response.Content.Headers)
            {
                responseHeaderText += h.Key + "=";
                foreach (var v in h.Value)
                    responseHeaderText += v + ";";
                responseHeaderText += "\r\n";
            }
            foreach (var h in response.Headers)
            {
                responseHeaderText += h.Key + "=";
                foreach (var v in h.Value)
                    responseHeaderText += v + ";";
                responseHeaderText += "\r\n";
            }

            Console.WriteLine(responseHeaderText);
            Console.ReadKey();
        }

        public static async Task<HttpResponseMessage> PostAsync(string uri, string param, IDictionary<string, string> header = null)
        {
            HttpClient client = new HttpClient();

            if (header != null && header.Count > 0)
            {
                foreach (var head in header)
                    client.DefaultRequestHeaders.TryAddWithoutValidation(head.Key, head.Value);
            }

            HttpContent content = null;
            if (header != null && header.ContainsKey("Content-Type"))
            {
                switch (header["Content-Type"])
                {
                    case "multipart/form-data":
                        content = new MultipartFormDataContent(param);
                        break;
                    case "application/x-www-form-urlencoded":
                        //content = new FormUrlEncodedContent(param);
                        break;
                    case "application/json":
                    case "application/text":
                    case "application/xml":
                        content = new StringContent(param, Encoding.UTF8, "application/json");
                        break;
                    default: break;
                }
            }
            return await client.PostAsync(uri, content);
        }
    }
}
